package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DBOpenHelper extends SQLiteOpenHelper {
    private SQLiteDatabase db;
    public  DBOpenHelper (Context context){

        super(context,"db_test",null,2);
        db = getReadableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(
                "CREATE TABLE IF NOT EXISTS user("+"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
                         "name TEXT," +
                         "email TEXT," +
                         "psw TEXT)"
        );

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);

    }
    public void add(String name,String email,String psw){
        db.execSQL("INSERT INTO user (name,psw,email) VALUES(?,?,?)",new Object[]{name,psw,email});
    }
    public void delete(String name,String psw){
        db.execSQL("DELETE FROM user WHERE name = AND password ="+name+psw);
    }
    public void update(String psw){
        db.execSQL("UPDATE user SET password = ?",new Object[]{psw});
    }

        ArrayList<User> getAllData(){
           ArrayList<User> list = new ArrayList<User>();
           @SuppressLint("Recycle") Cursor cursor = db.query("user",null,null,null,null,null,"name DESC");
           while (cursor.moveToNext()){
               @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
               @SuppressLint("Range") String psw = cursor.getString(cursor.getColumnIndex("psw"));
               @SuppressLint("Range")String email = cursor.getString(cursor.getColumnIndex("email"));


               list.add(new User(name,psw,email));

           }
           return list;
        }
    }




